package com.yuke.cloud.service.wmc.controller.frontend;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yuke.cloud.common.core.support.BaseController;
import com.yuke.cloud.common.util.PublicUtil;
import com.yuke.cloud.common.util.wrapper.WrapMapper;
import com.yuke.cloud.common.util.wrapper.Wrapper;
import com.yuke.cloud.service.api.omc.dto.OdsTeamSpecInfoDto;
import com.yuke.cloud.service.api.omc.service.OmcOrderFeignApi;
import com.yuke.cloud.service.api.wmc.dto.StorageSpecInfoDto;
import com.yuke.cloud.service.wmc.dto.WmsSpecGoodsDto;
import com.yuke.cloud.service.wmc.dto.WmsStorageProdDto;
import com.yuke.cloud.service.wmc.entity.WmsStorage;
import com.yuke.cloud.service.wmc.entity.WmsWarehouseShop;
import com.yuke.cloud.service.wmc.service.WmsAsyncService;
import com.yuke.cloud.service.wmc.service.WmsStorageSpecService;
import com.yuke.cloud.service.wmc.service.WmsWarehouseShopService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.http.MediaType;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>Company: Copyright (c) 2018. yuke All Rights Reserved. </br> </p>
 * <p>Title：yuke-mall </br> </p>
 * <p>com.yuke.cloud.service.wmc.controller.frontend Description TODO </br> </p>
 * @Author wg
 * @Date   2019/11/20 13:12
 */

@Slf4j
@Api(value = "WEB - ProdSpecController", tags = "处理ProdSpec相关请求", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@RestController
@RequestMapping("/mall/wms/spec")
@EnableAsync
public class MallWmsStorageSpecController extends BaseController {
    @Resource
    private WmsStorageSpecService wmsStorageSpecService;
    @Resource
    private WmsWarehouseShopService wmsWarehouseShopService;
    @Resource
    private OmcOrderFeignApi omcOrderFeignApi;
    @Resource
    private WmsAsyncService wmsAsyncService;

    @GetMapping("/app/recommend")
    @ApiOperation(httpMethod = "GET", value = "app首页商品推荐")
    public Wrapper<PageInfo<StorageSpecInfoDto>> recommendList(@ApiParam(name = "page", value = "分页值", defaultValue = "0") @RequestParam(defaultValue = "0") Integer page,
                                                           @ApiParam(name = "size", value = "每分页返回的记录数", defaultValue = "0") @RequestParam(defaultValue = "0") Integer size) {
        PageHelper.startPage(page, size);
        List<StorageSpecInfoDto> storageSpecInfoDtos = wmsStorageSpecService.getListRecommend();
        PageInfo pageInfo = new PageInfo(storageSpecInfoDtos);
        return WrapMapper.ok(pageInfo);
    }

    /**
     * 获取商品信息，先从wmc_storage取出对应库存商品数量、价格，再到pmc获取商品具体信息
     * B 端分类页、C 端分页类、品牌
     * @param page
     * @param size
     * @param shopId
     * @param storageSpecInfoDto
     * @return
     */
    @PostMapping("/app/condition")
    @ApiOperation(httpMethod = "POST", value = "app")
    public Wrapper<PageInfo<StorageSpecInfoDto>> getAppSpecByCondition(@ApiParam(name = "page", value = "分页值", defaultValue = "0") @RequestParam(defaultValue = "0") Integer page,
                                                                       @ApiParam(name = "size", value = "每分页返回的记录数", defaultValue = "0") @RequestParam(defaultValue = "0") Integer size,
                                                                       @ApiParam(name = "shopId", value = "附近店铺ID") @RequestParam(required = false) Long shopId,
                                                                       @RequestBody(required = false) StorageSpecInfoDto storageSpecInfoDto) {
        System.out.println("page="+page+",size="+size+",condition传入参数："+storageSpecInfoDto);
        if (storageSpecInfoDto.getSaleType() == null){
            return null;
        }
        // add by wg 20190611 对排序方式进行判断
        if (storageSpecInfoDto != null && storageSpecInfoDto.getSortPriceType() != null) {
            String sortPriceType = storageSpecInfoDto.getSortPriceType();
            if (!sortPriceType.equalsIgnoreCase("asc") && !sortPriceType.equalsIgnoreCase("desc")) {
                return null;
            }
        }
        if (storageSpecInfoDto != null && storageSpecInfoDto.getSortCountType() != null) {
            String sorCountType = storageSpecInfoDto.getSortCountType();
            if (!sorCountType.equalsIgnoreCase("asc") && !sorCountType.equalsIgnoreCase("desc")) {
                return null;
            }
        }

        List<Long> shopIds = new ArrayList<>();
        //由供应商的id（实际上是shopId）
        if (PublicUtil.isNotEmpty(storageSpecInfoDto.getSupplierId()) && storageSpecInfoDto.getSupplierId() > 0) {
            shopIds.add(storageSpecInfoDto.getSupplierId());
        } else {
            shopIds.add(shopId);
        }
        log.info("参数shopId={}", shopIds);
        List<WmsWarehouseShop> wmsWarehouseShops = wmsWarehouseShopService.getbyshopid(shopIds);
        if (wmsWarehouseShops != null && wmsWarehouseShops.size() > 0) {
            storageSpecInfoDto.setWarehouseId(wmsWarehouseShops.get(0).getWarehouseId());
        }
        //172291877306630144,180383802257571840
        //172291905962115072,172291940896473088,172291980486508544,172292008714174464,172292048597811200,
        //172292084618493952,180383853851705344,180383957396488192,180383998202871808,180384047804710912,180384236728745984,180384281641353216
        if (storageSpecInfoDto.getCategoryId() != null && storageSpecInfoDto.getCategoryId() != 0){
            //对拼单类的商品特殊处理
            if (storageSpecInfoDto.getCategoryId().equals(373532164140826624L)){
                return getStorageByTeamInfo(page,size,storageSpecInfoDto);
            }
            //对下面这些类的排序，按库存多少进行
            String str = "172291905962115072,172291940896473088,172291980486508544,172292008714174464,172292048597811200," +
                    "172292084618493952,180383853851705344,180383957396488192,180383998202871808," +
                    "180384047804710912,180384236728745984,180384281641353216";
            if (str.contains(storageSpecInfoDto.getCategoryId().toString())){
                storageSpecInfoDto.setSortStockType("desc");
            }
        }

        if (storageSpecInfoDto.getSaleType().equals((byte)1)){
            //按productId过滤specId
            PageHelper.startPage(page, size);
            storageSpecInfoDto.setIsEnable(true);
            System.out.println("AAAAAAAAAAAAAAAAAstorageSpecInfoDto="+storageSpecInfoDto);
            String strcoco = "172291014664126464,172291045676810240,172290736401416192,224849869285359616";
            List<StorageSpecInfoDto> storageSpecInfoDtoList  = new ArrayList<>();
            if (storageSpecInfoDto.getCategoryId() != null && strcoco.contains(storageSpecInfoDto.getCategoryId().toString()))
            {
                storageSpecInfoDtoList  =  wmsStorageSpecService.getAppStorageSpecByCondition(storageSpecInfoDto, shopId);
            }else if ( storageSpecInfoDto.getFactoryId() != null &&  storageSpecInfoDto.getFactoryId() > 0 )
            {
                storageSpecInfoDtoList  =  wmsStorageSpecService.getAppStorageSpecByCondition(storageSpecInfoDto, shopId);
            }else
             {
                storageSpecInfoDtoList  =  wmsStorageSpecService.getProductSpecByCondition(storageSpecInfoDto);
                if (PublicUtil.isEmpty(storageSpecInfoDtoList) ){
                    return WrapMapper.ok();
                }
            }

            PageInfo pageInfo = new PageInfo(storageSpecInfoDtoList);
            System.out.println("AAAAAAAAAAAAAAAAAstorageSpecInfoDto="+storageSpecInfoDtoList);
            List<StorageSpecInfoDto> storageSpecInfoDtos = wmsStorageSpecService.getStorageSpecExtra(storageSpecInfoDtoList);
            pageInfo.setList(storageSpecInfoDtos);
            System.out.println("AAAAAAAAAAAAAAAAAstorageSpecInfoDto="+storageSpecInfoDtos);
            return WrapMapper.ok(pageInfo);
        }else{
            PageHelper.startPage(page, size);
            List<StorageSpecInfoDto> storageSpecInfoDtoList  =  wmsStorageSpecService.getAppStorageSpecByCondition(storageSpecInfoDto, shopId);
            if (PublicUtil.isEmpty(storageSpecInfoDtoList) ){
                return WrapMapper.ok();
            }
            PageInfo pageInfo = new PageInfo(storageSpecInfoDtoList);

            List<StorageSpecInfoDto> storageSpecInfoDtos = wmsStorageSpecService.getSpecInfoExtra(shopId,storageSpecInfoDtoList,storageSpecInfoDto.getSaleType(),storageSpecInfoDto.getWarehouseId());
            pageInfo.setList(storageSpecInfoDtos);
            return WrapMapper.ok(pageInfo);
        }

    }

    /**
     * 获取所有商品,提供给订单录入页面，添加订单商品用，不判断isEnable，不判断价格是否为0
     * @param page
     * @param size
     * @param storageSpecInfoDto
     * @return
     */
    @PostMapping("/goods")
    @ApiOperation(httpMethod = "POST", value = "获取所有商品")
    public Wrapper<PageInfo<WmsSpecGoodsDto>>  getSpecGoods(@ApiParam(name = "page", value = "分页值", defaultValue = "0") @RequestParam(defaultValue = "0") Integer page,
                                                            @ApiParam(name = "size", value = "每分页返回的记录数", defaultValue = "0") @RequestParam(defaultValue = "0") Integer size,
                                                            @RequestBody(required = false) StorageSpecInfoDto storageSpecInfoDto){
        if ( null ==  storageSpecInfoDto.getWarehouseId() ){
            Long shopId = 220854931912392704L;
            if(storageSpecInfoDto.getShopId() !=null  ){
                shopId = storageSpecInfoDto.getShopId();
            }
            List<WmsWarehouseShop> warehouseShop = wmsWarehouseShopService.getbyshopid(Arrays.asList(shopId));
            Long warehouseId = (warehouseShop != null && warehouseShop.size() > 0 )? warehouseShop.get(0).getWarehouseId() : 6L;
            storageSpecInfoDto.setWarehouseId(warehouseId);
        }
        PageHelper.startPage(page, size);
        List<StorageSpecInfoDto> prodSpecGoods = wmsStorageSpecService.getProdSpecGoods(storageSpecInfoDto);
        int total = (int) new PageInfo<>(prodSpecGoods).getTotal();

        List<WmsSpecGoodsDto> wmsSpecGoodsDtos = new ArrayList<>();

        for (StorageSpecInfoDto item : prodSpecGoods){
            WmsSpecGoodsDto wmsSpecGoods = new WmsSpecGoodsDto();
            BeanUtils.copyProperties(item,wmsSpecGoods);
            wmsSpecGoods.setHasRebate(item.getHasRebate());
            wmsSpecGoods.setHasTying(item.getHasTying());
            wmsSpecGoods.setGoodsPrice(item.getStockPrice());
            wmsSpecGoods.setIsEnable(item.getIsEnable());
            wmsSpecGoods.setPicUrl(item.getBigPicture());
            wmsSpecGoodsDtos.add(wmsSpecGoods);

        }

        PageInfo pageInfo = new PageInfo(wmsSpecGoodsDtos);
        pageInfo.setTotal(total);
        return  WrapMapper.ok(pageInfo);
    }

    /**
     * C 端点击分类品牌获取商品,按productId折叠商品
     * @param page
     * @param size
     * @param shopId
     * @param prodCategoryBrandDto
     * @return
     */
    @PostMapping("/getproductpage")
    @ApiOperation(httpMethod = "POST", value = "App根据条件获取商品")
    public Wrapper<PageInfo<WmsStorageProdDto>> getProductPages(
            @ApiParam(name = "page", value = "分页值", defaultValue = "0") @RequestParam(defaultValue = "0")Integer page,
            @ApiParam(name = "size", value = "每分页返回的记录数", defaultValue = "0") @RequestParam(defaultValue = "0")Integer size,
            @ApiParam(name = "shopId", value = "店铺ID") @RequestParam(required = false) Long shopId,
            @ApiParam(name = "prodCategoryBrandDto", value = "App根据条件获取商品") @RequestBody(required = false) StorageSpecInfoDto prodCategoryBrandDto) {

        List<StorageSpecInfoDto>list = new ArrayList<>();
        List<WmsWarehouseShop> wmsWarehouseShops = wmsWarehouseShopService.getbyshopid(Arrays.asList(shopId));
        Long warehouseId = (wmsWarehouseShops != null && wmsWarehouseShops.size() > 0 )? wmsWarehouseShops.get(0).getWarehouseId() : 6L;
        prodCategoryBrandDto.setWarehouseId(warehouseId);

        if (prodCategoryBrandDto.getSaleType() == null){
            prodCategoryBrandDto.setSaleType((byte)1);
        }
        System.out.println("App根据条件获取商品"+prodCategoryBrandDto);

        if (prodCategoryBrandDto != null ){
            PageHelper.startPage(page, size);
            list = wmsStorageSpecService.getWmsCategoryBrand(prodCategoryBrandDto, shopId);
        }
        PageInfo pageInfo = new PageInfo(list);
        return WrapMapper.ok(pageInfo);
    }

    /** wmsStorage
     * warehouseId,specId
     * @param wmsStorage
     * @return
     */
    @PostMapping("/selectWmsStorage")
    @ApiOperation(httpMethod = "POST", value = "App根据条件获取商品")
    public Wrapper<List<WmsStorage>> getAllStorageBySpecIds(@RequestBody WmsStorage wmsStorage) {
        if (wmsStorage == null || wmsStorage.getWarehouseId() == null || wmsStorage.getSpecId() == null){
           return  WrapMapper.error("参数传递错误！");
        }
        List<WmsStorage> wmsStorageList = wmsStorageSpecService.select(wmsStorage);
        return WrapMapper.ok(wmsStorageList);
    }

    /**
     * 拼单购商品列表，包含商品信息，该商品的拼购信息正在拼单的人数
     */
    @PostMapping("/selectTeamSpecInfo")
    @ApiOperation(httpMethod = "POST", value = "App根据条件获取商品")
    public Wrapper<PageInfo<StorageSpecInfoDto>> getStorageByTeamInfo(
            @ApiParam(name = "page", value = "分页值", defaultValue = "0") @RequestParam(defaultValue = "0")Integer page,
            @ApiParam(name = "size", value = "每分页返回的记录数", defaultValue = "0") @RequestParam(defaultValue = "0")Integer size,
            @ApiParam(name = "storageSpecInfoDto", value = "App根据条件获取商品") @RequestBody StorageSpecInfoDto storageSpecInfoDto) {
        if (storageSpecInfoDto == null || storageSpecInfoDto.getWarehouseId() == null || storageSpecInfoDto.getCategoryId() == null){
            return  WrapMapper.error("参数传递错误！");
        }
        Long warehouseId = storageSpecInfoDto.getWarehouseId();
        //拼单购的ID=370937117763436544L
        Long categoryId = storageSpecInfoDto.getCategoryId();
        List<Long> categoryIds = Arrays.asList(categoryId);

        PageHelper.startPage(page, size);
        List<StorageSpecInfoDto> wmsStorageList = wmsStorageSpecService.getStorageInfoByCategoryIds(categoryIds,warehouseId);
        if (wmsStorageList == null || wmsStorageList.size() < 1){
            PageInfo pageInfo = new PageInfo(wmsStorageList);
            return WrapMapper.ok(pageInfo);
        }

        List<Long> specIds = wmsStorageList.stream().map(StorageSpecInfoDto::getSpecId).collect(Collectors.toList());

        wmsStorageList = wmsStorageSpecService.getStorageSpecExtra(wmsStorageList);

        List<OdsTeamSpecInfoDto> list = omcOrderFeignApi.selectTeamInfoBySpecIds(specIds,warehouseId);
        if (list == null || list.size() < 1) {
            PageInfo pageInfo = new PageInfo(wmsStorageList);
            return WrapMapper.ok(pageInfo);
        }

        for (StorageSpecInfoDto spec : wmsStorageList){
            for (OdsTeamSpecInfoDto item : list){
                if (spec.getSpecId().equals(item.getSpecId())){
                    spec.setOdsTeamSpecInfoDto(item);
                }

            }
        }

        PageInfo pageInfo = new PageInfo(wmsStorageList);
        return WrapMapper.ok(pageInfo);

    }

    /** wmsStorage
     * warehouseId,specId
     * @param wmsStorage
     * @return
     */
    @PostMapping("/selectWmsSpecsByProductId")
    @ApiOperation(httpMethod = "POST", value = "App根据条件获取商品")
    public Wrapper<List<WmsStorage>> selectWmsSpecsByProductId(@RequestBody WmsStorage wmsStorage) {
        if (wmsStorage == null || wmsStorage.getWarehouseId() == null || wmsStorage.getProductId() == null){
            return  WrapMapper.error("参数传递错误！");
        }
        List<WmsStorage> wmsStorageList = wmsStorageSpecService.select(wmsStorage);
        return WrapMapper.ok(wmsStorageList);
    }


}
